package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class SendAsyncService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public CompletableFuture<String> asyncSaveTimeLine(TimeLine timeLine) {
        try {
            Query query = Query.query(Criteria.where("userId").is(timeLine.getUserId()));
            List<Users> list = mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(list)) {
                //如果没有查到好友,也成功返回
                return CompletableFuture.completedFuture("ok");
            }
            for (Users users : list) {
                Long friendId = users.getFriendId();
                mongoTemplate.save(timeLine, "quanzi_time_line_" + friendId);
            }
        } catch (Exception e) {
            log.error("异步发送时间线表错误 userId=" + timeLine.getUserId());
            //如果发生错误,则回滚
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }
}
